<template>
  <div class="routes-management">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">配送路线管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增配送路线
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="路线名称">
          <el-input v-model="searchForm.name" placeholder="请输入路线名称" clearable />
        </el-form-item>
        <el-form-item label="起点">
          <el-input v-model="searchForm.origin" placeholder="请输入起点" clearable />
        </el-form-item>
        <el-form-item label="终点">
          <el-input v-model="searchForm.destination" placeholder="请输入终点" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="active" />
            <el-option label="停用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="code" label="路线编码" width="150" />
        <el-table-column prop="name" label="路线名称" width="200" />
        <el-table-column prop="origin" label="起点" width="150" />
        <el-table-column prop="destination" label="终点" width="150" />
        <el-table-column prop="distance" label="距离(km)" width="120" align="right" />
        <el-table-column prop="estimatedTime" label="预计时长" width="120" align="center">
          <template #default="{ row }">
            {{ row.estimatedTime }} 小时
          </template>
        </el-table-column>
        <el-table-column prop="passPoints" label="途经点" width="200">
          <template #default="{ row }">
            <el-tag v-for="(point, index) in row.passPoints.slice(0, 2)" :key="index" size="small" style="margin-right: 4px">
              {{ point }}
            </el-tag>
            <el-tag v-if="row.passPoints.length > 2" size="small" type="info">
              +{{ row.passPoints.length - 2 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="freight" label="运费(元)" width="120" align="right" />
        <el-table-column prop="frequency" label="频次" width="120" align="center" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              active-value="active"
              inactive-value="inactive"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleView(row)">
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <el-button link type="primary" size="small" @click="handleOptimize(row)">
              <el-icon><Aim /></el-icon>
              优化
            </el-button>
            <el-button link type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="900px"
      @close="handleDialogClose"
    >
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="路线编码" prop="code">
              <el-input v-model="formData.code" placeholder="请输入路线编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="路线名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入路线名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="起点" prop="origin">
              <el-input v-model="formData.origin" placeholder="请输入起点地址">
                <template #append>
                  <el-button :icon="LocationFilled" @click="selectLocation('origin')" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="终点" prop="destination">
              <el-input v-model="formData.destination" placeholder="请输入终点地址">
                <template #append>
                  <el-button :icon="LocationFilled" @click="selectLocation('destination')" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">途经点设置</el-divider>
        <el-form-item label="途经点">
          <div class="pass-points-wrapper">
            <div v-for="(point, index) in formData.passPoints" :key="index" class="pass-point-item">
              <el-input v-model="formData.passPoints[index]" placeholder="请输入途经点">
                <template #prepend>{{ index + 1 }}</template>
                <template #append>
                  <el-button :icon="Delete" @click="removePassPoint(index)" />
                </template>
              </el-input>
            </div>
            <el-button type="dashed" @click="addPassPoint" style="width: 100%">
              <el-icon><Plus /></el-icon>
              添加途经点
            </el-button>
          </div>
        </el-form-item>

        <el-divider content-position="left">路线信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="距离(km)" prop="distance">
              <el-input-number v-model="formData.distance" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计时长(h)" prop="estimatedTime">
              <el-input-number v-model="formData.estimatedTime" :min="0" :precision="1" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="运费(元)" prop="freight">
              <el-input-number v-model="formData.freight" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配送频次" prop="frequency">
              <el-select v-model="formData.frequency" placeholder="请选择配送频次">
                <el-option label="每日" value="daily" />
                <el-option label="隔日" value="alternate" />
                <el-option label="每周" value="weekly" />
                <el-option label="按需" value="ondemand" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 路线优化对话框 -->
    <el-dialog
      v-model="optimizeDialogVisible"
      title="路线优化"
      width="700px"
    >
      <el-alert
        title="路线优化建议"
        type="info"
        :closable="false"
        style="margin-bottom: 20px"
      >
        <div>基于当前交通状况和历史数据，为您生成优化方案</div>
      </el-alert>

      <div v-if="optimizeResult" class="optimize-result">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="原路线距离">{{ optimizeResult.originalDistance }} km</el-descriptions-item>
          <el-descriptions-item label="优化后距离">{{ optimizeResult.optimizedDistance }} km</el-descriptions-item>
          <el-descriptions-item label="原预计时长">{{ optimizeResult.originalTime }} 小时</el-descriptions-item>
          <el-descriptions-item label="优化后时长">{{ optimizeResult.optimizedTime }} 小时</el-descriptions-item>
          <el-descriptions-item label="距离节省" :span="2">
            <el-tag type="success">{{ optimizeResult.distanceSaved }} km ({{ optimizeResult.distanceSavedPercent }}%)</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="时间节省" :span="2">
            <el-tag type="success">{{ optimizeResult.timeSaved }} 小时 ({{ optimizeResult.timeSavedPercent }}%)</el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="left">优化建议</el-divider>
        <ul class="suggestions">
          <li v-for="(suggestion, index) in optimizeResult.suggestions" :key="index">
            {{ suggestion }}
          </li>
        </ul>
      </div>

      <template #footer>
        <el-button @click="optimizeDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="applyOptimize">应用优化方案</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Search, Refresh, Edit, Delete, View, Aim, LocationFilled
} from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  name: '',
  origin: '',
  destination: '',
  status: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增配送路线')
const formRef = ref(null)

// 表单数据
const formData = reactive({
  code: '',
  name: '',
  origin: '',
  destination: '',
  passPoints: [],
  distance: 0,
  estimatedTime: 0,
  freight: 0,
  frequency: '',
  remark: ''
})

// 优化对话框
const optimizeDialogVisible = ref(false)
const optimizeResult = ref(null)

// 表单验证规则
const rules = {
  code: [{ required: true, message: '请输入路线编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入路线名称', trigger: 'blur' }],
  origin: [{ required: true, message: '请输入起点', trigger: 'blur' }],
  destination: [{ required: true, message: '请输入终点', trigger: 'blur' }],
  distance: [{ required: true, message: '请输入距离', trigger: 'blur' }],
  estimatedTime: [{ required: true, message: '请输入预计时长', trigger: 'blur' }]
}

// 加载数据
const loadData = () => {
  loading.value = true
  
  setTimeout(() => {
    tableData.value = [
      {
        id: 1,
        code: 'RT001',
        name: '北京-上海快线',
        origin: '北京市朝阳区',
        destination: '上海市浦东新区',
        passPoints: ['天津市', '济南市', '徐州市', '南京市'],
        distance: 1200,
        estimatedTime: 15,
        freight: 500,
        frequency: '每日',
        status: 'active'
      },
      {
        id: 2,
        code: 'RT002',
        name: '广州-深圳专线',
        origin: '广州市天河区',
        destination: '深圳市南山区',
        passPoints: ['东莞市'],
        distance: 150,
        estimatedTime: 2,
        freight: 80,
        frequency: '每日',
        status: 'active'
      }
    ]
    pagination.total = 2
    loading.value = false
  }, 500)
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增配送路线'
  dialogVisible.value = true
}

// 查看详情
const handleView = (row) => {
  ElMessage.info(`查看配送路线: ${row.name}`)
}

// 路线优化
const handleOptimize = (row) => {
  optimizeDialogVisible.value = true
  
  // 模拟优化结果
  optimizeResult.value = {
    originalDistance: row.distance,
    optimizedDistance: row.distance * 0.9,
    originalTime: row.estimatedTime,
    optimizedTime: row.estimatedTime * 0.85,
    distanceSaved: (row.distance * 0.1).toFixed(2),
    distanceSavedPercent: 10,
    timeSaved: (row.estimatedTime * 0.15).toFixed(1),
    timeSavedPercent: 15,
    suggestions: [
      '建议调整途经点顺序，避开拥堵路段',
      '推荐使用高速公路，可节省约1小时',
      '建议在凌晨2-5点出发，道路通畅',
      '可考虑增加一个中转站，提高配送效率'
    ]
  }
}

// 应用优化方案
const applyOptimize = () => {
  ElMessage.success('已应用优化方案')
  optimizeDialogVisible.value = false
  loadData()
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑配送路线'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该配送路线吗？', '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
    loadData()
  })
}

// 状态改变
const handleStatusChange = (row) => {
  const status = row.status === 'active' ? '启用' : '停用'
  ElMessage.success(`已${status}配送路线: ${row.name}`)
}

// 选择位置
const selectLocation = (type) => {
  ElMessage.info('地图选点功能')
}

// 添加途经点
const addPassPoint = () => {
  formData.passPoints.push('')
}

// 删除途经点
const removePassPoint = (index) => {
  formData.passPoints.splice(index, 1)
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success(dialogTitle.value === '新增配送路线' ? '创建成功' : '更新成功')
      dialogVisible.value = false
      loadData()
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
  formData.passPoints = []
}

// 分页改变
const handleSizeChange = () => {
  loadData()
}

const handleCurrentChange = () => {
  loadData()
}

onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.routes-management {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 16px;
      font-weight: 500;
    }
  }

  .search-form {
    margin-bottom: 20px;
  }

  .pass-points-wrapper {
    width: 100%;

    .pass-point-item {
      margin-bottom: 12px;
    }
  }

  .optimize-result {
    .suggestions {
      list-style: none;
      padding: 0;
      margin: 0;

      li {
        padding: 8px 0;
        padding-left: 20px;
        position: relative;

        &:before {
          content: '•';
          position: absolute;
          left: 0;
          color: #409eff;
          font-weight: bold;
        }
      }
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

